/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.baicaix.chat.views;

import java.awt.Component;
import java.beans.PropertyVetoException;
import javax.swing.JInternalFrame;
import org.baicaix.chat.ChatConstants;
import org.baicaix.chat.MainFrame;
import org.puremvc.java.interfaces.INotification;
import org.puremvc.java.patterns.mediator.Mediator;

/**
 *
 * @author baicaix
 */
public class MainFrameMediator extends Mediator {

    public MainFrameMediator(String mediatorName, Component viewComponent) {
        super(mediatorName, viewComponent);
    }

    @Override
    public String[] listNotificationInterests() {
        return new String[]{
            ChatConstants.CREATE_FRAME,
            ChatConstants.EXIT,
            ChatConstants.SEND_TO_FRAME,
            ChatConstants.LOGIN_SUCESS,
        };
    }

    @Override
    public void handleNotification(INotification noti) {
        System.out.println("MainFrameMediator receive:"+noti.getName());
        super.handleNotification(noti);
        if (ChatConstants.CREATE_FRAME.equals(noti.getName())) {
            doCreateFrame((JInternalFrame)noti.getBody());
        } else if (ChatConstants.SEND_TO_FRAME.equals(noti.getName())) {
            showLogAndSendToClient((String)noti.getBody(), noti.getType());
        } else if (ChatConstants.EXIT.equals(noti.getName())) {
            doExit();
        } else if (ChatConstants.LOGIN_SUCESS.equals(noti.getName())) {
            getMainFrame().setVisible(true);
        }
    }

    private int locationX = 100;
    /**
     * 显示消息窗口
     * @param interFrame
     */
    private void doCreateFrame(JInternalFrame interFrame) {
            interFrame.setSize(360, 300);
            interFrame.setClosable(true);
            interFrame.setMaximizable(true);
            interFrame.setIconifiable(true);
            interFrame.setResizable(true);
            MainFrame mainFrame = this.getMainFrame();
            mainFrame.getDesktop().add(interFrame, 100);

            interFrame.setLocation(locationX, 0);
            locationX += 100;
            if (locationX >= mainFrame.getWidth()) {
                locationX = 0;
            }
            try {
                interFrame.setSelected(true);
            } catch (PropertyVetoException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            interFrame.setVisible(true);
    }

    private void showLogAndSendToClient(String msg, String name) {
        getMainFrame().showLog(msg);
        facade.sendNotification(ChatConstants.RECEIVE_FROM_FRAME, msg, name);
    }

    private void doExit() {
        System.exit(1);
    }

    private MainFrame getMainFrame() {
        return (MainFrame)viewComponent;
    }
}
